package com.laboratory.manage.utils;

import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: qinaolong
 * @Date: 2023/06/02/16:15
 * @Description:
 */
public class UploadImageUtils {

    public static File UploadImage(MultipartFile file, String type) throws Exception {

        //获取正在处理的文件的原始文件名
        //String originalFilename = file.getOriginalFilename();

        //通过将当前系统时间（以毫秒为单位）附加到原始文件名上生成一个新的文件名,这样做可以确保文件名的唯一性。
        //String newName =  System.currentTimeMillis() + originalFilename;

        //从原始文件名中提取文件扩展名。然后，将提取的扩展名与点号（"."）拼接起来创建后缀
        //String suffix = "." + FilenameUtils.getExtension(originalFilename);

        //获取文件的大小，并将其转化为字符串
        //String size = String.valueOf(file.getSize());

        //创建一个File对象，表示项目的根路径  获取类路径（classpath）的 URL
        String path = ResourceUtils.getURL("classpath:").getPath();
        path = java.net.URLDecoder.decode(path, "utf-8");
        File rootPath = new File(path);
        //File rootPath = new File(ResourceUtils.getURL("classpath:").getPath());
        //System.out.println("rootPath: " + rootPath);

        //检查根路径是否存在
        if(!rootPath.exists()){
            rootPath = new File("");
        }

        //得到根路径的绝对路径
        File parentFilePath = rootPath.getAbsoluteFile();
        //System.out.println("parentFilePath: " + parentFilePath);

        //检查父路径是否存在，如果不存在，那么就创建该父路径
        if(!parentFilePath.exists()){
            parentFilePath.mkdir();
        }

        //创建一个表示上传路径的 File 对象
        File uploadPath = new File(parentFilePath.getAbsolutePath(), "static/uploadImages/" + type + "/");
        //System.out.println("uploadPath: " + uploadPath);

        if(!uploadPath.exists()){
            uploadPath.mkdirs();
        }

        return uploadPath;
    }
}
